/**
 * 微博超话自动签到插件 V1.6.1
 * Created by MapleX
 * content.js - 内容脚本
 */

// 滚动到底部加载所有超话
async function scrollToLoadAll() {
  return new Promise((resolve) => {
    let lastHeight = document.documentElement.scrollHeight;
    let scrollAttempts = 0;
    const maxAttempts = 10; // 最大尝试次数
    
    function scroll() {
      window.scrollTo(0, document.documentElement.scrollHeight);
      setTimeout(() => {
        const newHeight = document.documentElement.scrollHeight;
        if (newHeight > lastHeight && scrollAttempts < maxAttempts) {
          // 高度变化，说明加载了新内容
          lastHeight = newHeight;
          scrollAttempts++;
          scroll();
        } else {
          // 高度不变或达到最大尝试次数，认为已加载完成
          window.scrollTo(0, 0); // 滚回顶部
          resolve();
        }
      }, 2000); // 等待2秒让新内容加载
    }
    
    scroll();
  });
}

function autoCheckIn() {
  return new Promise((resolve) => {
    // 等待页面完全加载
    function waitForButton(retryCount = 0, maxRetries = 15) { // 增加重试次数
      // 尝试多个可能的选择器来查找签到按钮
      const checkInButton = document.querySelector('a[action-type="widget_take"]') || 
                           document.querySelector('.W_btn_b.btn_32px') ||
                           document.querySelector('.btn_bed .W_btn_b') ||
                           document.querySelector('a[action-data*="checkin"]') ||  // 新增选择器
                           document.querySelector('a.W_btn_b'); // 新增选择器

      if (checkInButton) {
        const buttonText = checkInButton.querySelector('span')?.textContent?.trim() ||
                          checkInButton.textContent?.trim();
        
        if (buttonText === '签到') {
          console.log('找到签到按钮，开始签到');
          try {
            // 尝试多种点击方法
            const clickMethods = [
              // // 方法1: 模拟真实的点击事件序列
              // () => {
              //   ['mouseenter', 'mousedown', 'mouseup', 'click'].forEach(eventType => {
              //     const event = new MouseEvent(eventType, {
              //       view: window,
              //       bubbles: true,
              //       cancelable: true,
              //       clientX: checkInButton.getBoundingClientRect().left + 10,
              //       clientY: checkInButton.getBoundingClientRect().top + 10
              //     });
              //     checkInButton.dispatchEvent(event);
              //   });
              // },
              // // 方法2: 直接点击
              // () => checkInButton.click(),
              // 方法3: 触发原生点击事件
              () => {
                const event = new Event('click', { bubbles: true });
                checkInButton.dispatchEvent(event);
              },
              // 方法4: 模拟鼠标事件
              () => {
                const event = new MouseEvent('click', {
                  bubbles: true,
                  cancelable: true,
                  view: window
                });
                checkInButton.dispatchEvent(event);
              },
              // 方法5: 使用 HTMLElement 的 click 方法
              () => HTMLElement.prototype.click.call(checkInButton)
            ];
            
            // 等待签到结果
            let checkAttempts = 0;
            const maxAttempts = 10; // 增加等待次数
            let currentMethodIndex = 0;
            
            const checkInterval = setInterval(() => {
              const newButtonText = checkInButton.querySelector('span')?.textContent?.trim() ||
                                  checkInButton.textContent?.trim();
              console.log('检查签到状态:', newButtonText);
              
              if (newButtonText === '已签到') {
                clearInterval(checkInterval);
                chrome.storage.local.set({ 
                  status: '签到成功！'
                });
                resolve(true); // 签到成功
              } else if (checkAttempts >= maxAttempts) {
                clearInterval(checkInterval);
                // 如果当前方法失败，尝试下一个方法
                if (currentMethodIndex < clickMethods.length) {
                  console.log(`尝试第 ${currentMethodIndex + 1} 种点击方法`);
                  try {
                    clickMethods[currentMethodIndex]();
                  } catch (error) {
                    console.error('点击方法失败:', error);
                  }
                  currentMethodIndex++;
                  checkAttempts = 0; // 重置尝试次数
                } else {
                  chrome.storage.local.set({ 
                    status: '签到失败！'
                  });
                  resolve(false); // 所有方法都失败
                }
              }
              checkAttempts++;
            }, 500);
          } catch (error) {
            console.error('签到出错:', error);
            // 如果出错，重试整个过程
            if (retryCount < maxRetries) {
              console.log(`签到出错，等待后重试 (${retryCount + 1}/${maxRetries})`);
              setTimeout(() => waitForButton(retryCount + 1, maxRetries), 2000);
            } else {
              chrome.storage.local.set({ 
                status: '签到失败！'
              });
              resolve(false);
            }
          }
        } else if (buttonText === '已签到') {
          console.log('已经签到过了');
          resolve(true);
        } else {
          console.log('按钮文本异常:', buttonText);
          if (retryCount < maxRetries) {
            console.log(`等待后重试 (${retryCount + 1}/${maxRetries})`);
            setTimeout(() => waitForButton(retryCount + 1, maxRetries), 2000);
          } else {
            chrome.storage.local.set({ 
              status: '签到失败！'
            });
            resolve(false);
          }
        }
      } else {
        if (retryCount < maxRetries) {
          console.log(`等待按钮出现 (${retryCount + 1}/${maxRetries})`);
          setTimeout(() => waitForButton(retryCount + 1, maxRetries), 2000);
        } else {
          console.log('重试次数用完，仍未找到签到按钮');
          chrome.storage.local.set({ 
            status: '未找到签到按钮'
          });
          resolve(false);
        }
      }
    }

    // 开始等待按钮
    waitForButton();
  });
}

async function getAllSuperTopics() {
  // 先滚动加载所有超话
  await scrollToLoadAll();
  
  // 然后获取所有超话链接
  const superTopicLinks = document.querySelectorAll('a.ALink_none_1w6rm.TopicFeedCard_left_EgdGf');
  const foundTopics = Array.from(superTopicLinks).map(link => {
    return {
      url: link.getAttribute('href').startsWith('//') ? 
        'https:' + link.getAttribute('href') : link.getAttribute('href'),
      name: link.querySelector('.TopicFeedCard_cla_1pQ6t')?.textContent?.trim() || '未知超话'
    };
  }).filter(topic => topic.url);
  
  if (foundTopics.length > 0) {
    console.log('找到超话：', foundTopics.length, '个');
    // 保存检索到的超话
    chrome.storage.local.set({ foundTopics });
    // 发送链接给 background 处理
    chrome.runtime.sendMessage({
      action: 'processSuperTopics',
      urls: foundTopics.map(topic => topic.url)
    });
  } else {
    console.log('未找到超话链接');
    chrome.storage.local.set({ foundTopics: [] });
  }
}

// 修改消息监听器
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.action === 'checkIn') {
    autoCheckIn().then(success => {
      sendResponse({ success: success });
    });
    return true; // 保持消息通道开启
  } else if (request.action === 'getAllSuperTopics') {
    getAllSuperTopics();
    return true; // 保持消息通道开启
  } else if (request.action === 'getTopicTitle') {
    setTimeout(() => {
      const title = document.querySelector('.username')?.textContent?.trim();
      console.log('获取到超话标题:', title);
      sendResponse({ title: title });
    }, 3000);
    return true; // 保持消息通道开启
  }
}); 